from fastapi import FastAPI, UploadFile, File, Form, HTTPException
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi import Request
import uvicorn
import os
from pathlib import Path
from typing import Optional
import mysql.connector
from datetime import datetime
import json
import magic
from PIL import Image
import io
from .interface_ai.ai_processor import ai_processor

app = FastAPI()

# 创建必要的目录
UPLOAD_DIR = Path("uploads")
UPLOAD_DIR.mkdir(exist_ok=True)

# 挂载静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")

# 数据库配置
DB_CONFIG = {
    "host": "localhost",
    "user": "root",
    "password": "your_password",
    "database": "qa_system"
}

def get_db_connection():
    return mysql.connector.connect(**DB_CONFIG)

@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
    try:
        # 读取文件内容
        contents = await file.read()
        
        # 检测文件类型
        file_type = magic.from_buffer(contents, mime=True)
        
        # 生成唯一文件名
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"{timestamp}_{file.filename}"
        file_path = UPLOAD_DIR / filename
        
        # 保存文件
        with open(file_path, "wb") as f:
            f.write(contents)
            
        # 如果是图片，处理并保存缩略图
        if file_type.startswith('image/'):
            img = Image.open(io.BytesIO(contents))
            img.thumbnail((800, 800))
            thumb_path = UPLOAD_DIR / f"thumb_{filename}"
            img.save(thumb_path)
            
        # 保存到数据库
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute(
            "INSERT INTO files (filename, file_type, file_path, upload_time) VALUES (%s, %s, %s, %s)",
            (filename, file_type, str(file_path), datetime.now())
        )
        conn.commit()
        cursor.close()
        conn.close()
        
        return {"message": "File uploaded successfully", "filename": filename}
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/ask")
async def ask_question(question: str = Form(...)):
    try:
        # 使用AI处理器处理问题
        response = ai_processor.process_question(question)
        
        # 保存问答记录到数据库
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute(
            "INSERT INTO qa_records (question, answer, confidence, processing_time, created_at) VALUES (%s, %s, %s, %s, %s)",
            (question, response["answer"], response["confidence"], response["processing_time"], datetime.now())
        )
        conn.commit()
        cursor.close()
        conn.close()
        
        return JSONResponse(content=response)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) 